import {Injectable} from '@angular/core';
import {AppConfig} from '../config';
import {Headers, Http} from '@angular/http';
import {Permission} from '../entity/permission.model';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class PermissionService {
  private readonly param = 'permissions';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }


  /**
   * 获取所有
   *
   * @returns {Promise<Permission[]>}
   * @memberof PermissionService
   */
  getPermissions(): Promise<Permission[]> {
    return this.http.get(`${this.url}`)
      .toPromise()
      .then(res => res.data as Permission[])
      .catch(this.handleError);
  }


  batchDelete(valueIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${valueIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return true;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }


  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }

}


// WEBPACK FOOTER //
// ./src/app/service/permission.service.ts
